package pl.umk.mat.fred.unicore.urc.storagemanagement.dialogs;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.BelowStorageNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.BelowStorageNode.OldPermissions;

public class ChangePermissionsDialog extends Dialog {

	private OldPermissions permissions;
	private OldPermissions newPermissions;
	
	private Button rCheckBox;
	private Button wCheckBox;
	private Button xCheckBox;
	
	private Boolean r;
	private Boolean w;
	private Boolean x;
	
	private boolean changed;
	
	public ChangePermissionsDialog(Shell parent, OldPermissions permissions) {
	  super(parent);
	  this.permissions = permissions;
  }
	
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = (Composite)super.createDialogArea(parent);
		RowLayout layout = new RowLayout(SWT.VERTICAL);
		layout.marginLeft = 10;
		layout.marginRight = 10;
		composite.setLayout(layout);
		if (permissions == null) {
			Label message = new Label(composite, SWT.NONE);
			message.setText("You are modifying many files simultaneously,");
			Label message2 = new Label(composite, SWT.NONE);
			message2.setText("which have different permissions");
		}
		
		rCheckBox = new Button(composite, SWT.CHECK);
		rCheckBox.setText("Read");
		if (permissions != null) {
			rCheckBox.setSelection(permissions.getR());
		}
		
		wCheckBox = new Button(composite, SWT.CHECK);
		wCheckBox.setText("Write");
		if (permissions != null) {
			wCheckBox.setSelection(permissions.getW());
		}
		
		xCheckBox = new Button(composite, SWT.CHECK);
		xCheckBox.setText("Execute");
		if (permissions != null) {
			xCheckBox.setSelection(permissions.getX());
		}
		
		return composite;
	}
	
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
	}
	
	private void saveInput() {
		newPermissions = new BelowStorageNode.OldPermissions(rCheckBox.getSelection(), wCheckBox.getSelection(), xCheckBox.getSelection());
		changed = (permissions == null) || (!newPermissions.getR().equals(permissions.getR()) || !newPermissions.getW().equals(permissions.getW()) || !newPermissions.getX().equals(permissions));
	}
	
	public boolean isChanged() {
		return changed;
	}
	
	@Override
	protected void okPressed() {
		saveInput();
		super.okPressed();
	}
	
	public OldPermissions getPermissions() {
		return newPermissions;
	}

}
